const UserModel = require('../models/userModel');
const { success, error } = require('../utils/response');

const AuthController = {
  // 用户注册
  register: async (req, res) => {
    try {
      const { username, password, email, phone } = req.body;
      
      if (!username || !password || !email) {
        return error(res, '用户名、密码和邮箱为必填项', 400);
      }
      
      const userId = await UserModel.register(username, password, email, phone);
      success(res, { userId }, '注册成功');
    } catch (err) {
      console.error(err);
      error(res, '注册失败', 500);
    }
  },
  
  // 用户登录
  login: async (req, res) => {
    try {
      const { username, password } = req.body;
      
      if (!username || !password) {
        return error(res, '用户名和密码为必填项', 400);
      }
      
      const user = await UserModel.login(username, password);
      
      if (!user) {
        return error(res, '用户名或密码错误', 401);
      }
      
      success(res, {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        avatar: user.avatar,
        token: user.token
      }, '登录成功');
    } catch (err) {
      console.error(err);
      error(res, '登录失败', 500);
    }
  },
  
  // 获取当前用户信息
  getUserInfo: async (req, res) => {
    try {
      const userId = req.user.id;
      const user = await UserModel.getUserById(userId);
      
      if (!user) {
        return error(res, '用户不存在', 404);
      }
      
      // 移除敏感信息
      const { password, ...userInfo } = user;
      success(res, userInfo);
    } catch (err) {
      console.error(err);
      error(res, '获取用户信息失败', 500);
    }
  },
  
  // 更新用户信息
  updateUserInfo: async (req, res) => {
    try {
      const userId = req.user.id;
      const { username, email, phone, avatar } = req.body;
      
      const updateData = {
        username: username || req.user.username,
        email: email || req.user.email,
        phone: phone || req.user.phone,
        avatar: avatar || req.user.avatar
      };
      
      const successUpdate = await UserModel.updateUser(userId, updateData);
      
      if (!successUpdate) {
        return error(res, '更新用户信息失败', 500);
      }
      
      success(res, null, '用户信息更新成功');
    } catch (err) {
      console.error(err);
      error(res, '更新用户信息失败', 500);
    }
  },
  
  // 更新密码
  updatePassword: async (req, res) => {
    try {
      const userId = req.user.id;
      const { oldPassword, newPassword } = req.body;
      
      if (!oldPassword || !newPassword) {
        return error(res, '旧密码和新密码为必填项', 400);
      }
      
      const successUpdate = await UserModel.updatePassword(userId, oldPassword, newPassword);
      
      if (!successUpdate) {
        return error(res, '旧密码错误或更新失败', 401);
      }
      
      success(res, null, '密码更新成功');
    } catch (err) {
      console.error(err);
      error(res, '密码更新失败', 500);
    }
  }
};

module.exports = AuthController;